package cn.com.chengmandian.core.web.utils;

import cn.com.chengmandian.core.common.enums.ClientsEnum;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.com.chengmandian.core.web.pojo.CompanyInfo;
import cn.com.chengmandian.core.web.pojo.CompanyUser;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;

import java.util.HashMap;
import java.util.Map;

public class CompanyTokenUtil {
    private CompanyUser companyUser;

    private CompanyInfo companyInfo;

    private ClientsEnum clientsEnum;

    private Map<String, Object> attrs;

    public CompanyTokenUtil(CompanyUser companyUser, CompanyInfo companyInfo, ClientsEnum clientsEnum) {
        this.companyUser = companyUser;
        this.clientsEnum = clientsEnum;
        this.companyInfo = companyInfo;
    }

    public static CompanyTokenUtil create(CompanyUser companyUser, CompanyInfo companyInfo, ClientsEnum clientsEnum) {
        return new CompanyTokenUtil(companyUser, companyInfo, clientsEnum);
    }

    public CompanyTokenUtil setAttr(String key, Object value) {
        if (this.attrs == null) this.attrs = new HashMap<>();
        this.attrs.put(key, value);
        return this;
    }

    public String build() {
        companyUser.setAttrs(attrs);
        companyUser.setExpireDate(DateUtil.offsetDay(DateUtil.date(), clientsEnum.getExpireDay()).getTime());

        // 设置头部信息
        Map<String, Object> headers = new HashMap<>(2);
        headers.put("Type", "Jwt");
        headers.put("alg", "HS256");
        return JWTUtil.createToken(headers, BeanUtil.beanToMap(companyUser), companyInfo.getTokenSecret().getBytes());
    }
}
